package cn.qiyu5522.tk_ems.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.tk_ems.entity.Department;
import cn.qiyu5522.tk_ems.entity.Major;
import cn.qiyu5522.tk_ems.entity.Student;
import cn.qiyu5522.tk_ems.entity.vo.DepartmentVo;
import cn.qiyu5522.tk_ems.entity.dto.QueryParamDTO;
import cn.qiyu5522.tk_ems.mapper.DepartmentMapper;
import cn.qiyu5522.tk_ems.mapper.MajorMapper;
import cn.qiyu5522.tk_ems.mapper.StudentMapper;
import cn.qiyu5522.tk_ems.result.CustomMapResult;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.retrofit.IdGeneratorApi;
import cn.qiyu5522.tk_ems.service.DepartmentService;
import cn.qiyu5522.tk_ems.utils.RedisKey;
import cn.qiyu5522.tk_ems.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2023-02-04
 */
@Slf4j
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private IdGeneratorApi idGeneratorApi;
    @Resource
    private MajorMapper majorMapper;
    @Resource
    private RedisUtil redisUtil;


    @Override
    public R queryDepartmentByPageCondition(QueryParamDTO<DepartmentVo> queryParamDTO) {
        DepartmentVo condition = queryParamDTO.getCondition();
        IPage<Department> departmentIPage = new Page<Department>(queryParamDTO.getCurrentPage(), queryParamDTO.getPageSize());
        LambdaQueryWrapper<Department> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(condition.getName()), Department::getName, condition.getName());
        baseMapper.selectPage(departmentIPage, lambdaQueryWrapper);
        Map<String, Object> map = CustomMapResult.packagingResult(departmentIPage.getRecords(), queryParamDTO.getCurrentPage(), queryParamDTO.getPageSize(), departmentIPage.getTotal());
        return R.ok().data("departmentIPage", map);
    }

    @Override
    public R saveMore(List<DepartmentVo> departmentVos) {
        // 待添加的学生信息集合
        List<Department> departments = new ArrayList<>(departmentVos.size());
        Department department = null;
        for (DepartmentVo departmentVo : departmentVos) {
            // 对象转换将VO类型转为实体类型
            department = new Department();
            BeanUtils.copyProperties(departmentVo, department);
            // 院系表id自增长
            departments.add(department);
        }
        // 添加
        Integer integer = baseMapper.insertBatchSomeColumn(departments);
        // 添加成功，刷新Redis中的缓存
        if(integer>0){
            // 查询全部的院系数据
            QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "name");
            List<Department> departmentList = baseMapper.selectList(queryWrapper);
            redisUtil.set(RedisKey.DEPARTMENT_ID_AND_NAME,departmentList,RedisKey.EXPIRE_ONE_DAY);
        }
        return integer > 0 ? R.ok().message("院系添加成功") : R.error().message("院系添加失败");
    }

    @Override
    public R removeMore(List<Long> ids) {
        LambdaQueryWrapper<Student> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Student::getDepartmentId,ids);
        List<Student> students = studentMapper.selectList(lambdaQueryWrapper);
        LambdaQueryWrapper<Major> majorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        majorLambdaQueryWrapper.in(Major::getDepartmentId,ids);
        List<Major> majors = majorMapper.selectList(majorLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(students) || CollectionUtil.isNotEmpty(majors)) {
            return R.error().message("该院系下存在关联数据无法删除");
        }
        int i = baseMapper.deleteBatchIds(ids);
        if(i>0){
            // 更新Redis 里的值
            QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "name");
            List<Department> departmentList = baseMapper.selectList(queryWrapper);
            redisUtil.set(RedisKey.DEPARTMENT_ID_AND_NAME, departmentList, RedisKey.EXPIRE_ONE_DAY);
        }
        return i > 0 ? R.ok().message("院系删除成功") : R.error().message("院系删除失败");
    }

    @Override
    public List<Department> getForIdAndName() {
        List<Department> departments = new ArrayList<>();
        log.info("从Redis中拿取 院系编号与名称列表");
        departments = (List<Department>) redisUtil.get(RedisKey.DEPARTMENT_ID_AND_NAME);
        if (CollectionUtil.isEmpty(departments)) {
            log.info("Redis中无 院系编号与名称列表 ");
            // 将院系的编号与名称存入
            QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "name");
            departments = baseMapper.selectList(queryWrapper);
            if (departments.size() != 0) {
                log.info("将 院系编号与名称列表 存入redis");
                redisUtil.set(RedisKey.DEPARTMENT_ID_AND_NAME, departments, RedisKey.EXPIRE_ONE_DAY);
            }
        }
        return departments;

    }

    @Override
    public R queryByName(String name) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(name),"name",name);
        List<Department> departments = baseMapper.selectList(queryWrapper);
        return departments.size() == 0?
                R.ok().message("名称可用").data("flag",true):
                R.ok().message("名称不可用").data("flag",false);
    }
}
